# -*- coding: utf_8 -*-
# @Time : 2021/8/12 0012 12:16
# @Author : lyw
# @Remark : 门禁人员
import re
import logging

from db.common.IOTManager.Janitor.personnel import PersonnelDB

from mxsoftpy import Server

from model.common.IOTManager.Janitor.personnel import PersonnelModel
from utils.public.params_method import get_pagination_params, pagination


class PersonnelServer(Server):
    __model__ = PersonnelModel
    __db__ = PersonnelDB

    def get_personnel(self, **kwargs):
        print(kwargs)
        param = self.model(**kwargs).dict()
        sound = self.db.query_personnel(is_del=0, page_size=1, page_index=1)[1]
        if sound:
            if sound[0].get('badge_number'):
                param["sortkey"] = "badge_number"
            else:
                param["sortkey"] = "name"
            param["sortop"] = 0
        param["search"] = param["search"].replace("*", "")
        if kwargs.get("type"):
            query_param = {"order_by": "create_time", "is_desc": True}
        else:
            param["pagesize"] = param["page_size"]
            param["pageindex"] = param["page_index"]
            query_param = get_pagination_params(param)
        query_param["door_id"] = param["door_id"]
        if re.match("^[\u4e00-\u9fa5_a-zA-Z]+$", param["search"]):
            query_param["name__like"] = "*" + param["search"] + "*"
        elif re.match("^[a-zA-Z0-9]+$", param["search"]):
            query_param["badge_number__like"] = "*" + param["search"] + "*"
        else:
            query_param["name__like"] = "*" + param["search"] + "*"
        if param.get("identifier") < 2:
            query_param["is_del"] = 0 if param["identifier"] == 1 else 1
        # return query_param
        logging.info(f'门禁人员查询条件{query_param}', )
        total, res_list = self.db.query_personnel(kwargs.get("type"), **query_param)
        res_dict = {"data": res_list, "total": total}
        return pagination(res_dict, query_param, total)
